<script setup>
import { ref } from 'vue';

// 定义组件可以触发的事件
const emit = defineEmits(['send-message']);

// 输入框内容
const message = ref('');

// 发送消息给父组件
const sendMessage = () => {
  if (message.value.trim()) {
    emit('send-message', message.value);
    message.value = '';
  }
};

// 发送带额外参数的消息
const sendComplexMessage = () => {
  const complexData = {
    content: '这是一条复杂消息',
    timestamp: new Date().toLocaleString(),
    priority: 'high'
  };
  emit('send-message', JSON.stringify(complexData, null, 2));
};
</script>

<template>
  <div class="child-to-parent">
    <div class="message-input-section">
      <label for="message-input">输入消息：</label>
      <input
        id="message-input"
        v-model="message"
        type="text"
        placeholder="请输入要发送给父组件的消息"
        class="message-input"
      />
      <button 
        class="send-btn" 
        @click="sendMessage"
        :disabled="!message.trim()"
      >
        发送消息
      </button>
    </div>
    
    <div class="quick-actions">
      <button class="action-btn" @click="sendComplexMessage">
        发送复杂数据
      </button>
      <button class="action-btn" @click="emit('send-message', '这是通过按钮直接发送的消息')">
        快速发送示例消息
      </button>
    </div>
  </div>
</template>

<style scoped>
.child-to-parent {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.message-input-section {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.message-input-section label {
  font-weight: 500;
  color: #333;
}

.message-input {
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
}

.message-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.send-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 0.8rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.3s ease;
}

.send-btn:hover:not(:disabled) {
  background: #764ba2;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.quick-actions {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.action-btn {
  background: #4caf50;
  color: white;
  border: none;
  padding: 0.8rem 1.2rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.3s ease;
}

.action-btn:hover {
  background: #45a049;
}
</style>